﻿@page "/login"

@using System.ComponentModel.DataAnnotations;
@inject HttpClient HttpClient;
@inject IConfiguration configure
@inject NavigationManager NavigationManager
@inject IJSRuntime  JSRuntime
@inject MessageService _message

<div class="login-form">
    <Form Model="@model"
          OnFinish="OnFinish"
          OnFinishFailed="OnFinishFailed"
          LabelColSpan="8"
          WrapperColSpan="16">
        <FormItem Label="用户名">
            <Input @bind-Value="@context.Username" />
        </FormItem>
        <FormItem Label="密码">
            <InputPassword @bind-Value="@context.Password" />
        </FormItem>
        <FormItem WrapperColOffset="8" WrapperColSpan="16">
            <Button Type="@ButtonType.Primary" HtmlType="submit">
                登录
            </Button>
        </FormItem>
    </Form>
</div>

<style>
    .login-form {
        width: 20%;
        float: right;
        margin-right: 825px;
        padding-top: 45px;
    }
</style>

@code
{
    public string SelfUrl => configure.GetSection("App")["SelfUrl"];
    public string AuthUrl => configure.GetSection("AuthServer")["Authority"];

    public class Model
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

    public class LoginResultDto
    {
        public int Result { get; set; }
        public string Description { get; set; }
    }

    private Model model = new Model();

    protected override async Task OnInitializedAsync()
    {
        if (!string.IsNullOrEmpty(await JSRuntime.InvokeAsync<string>("localStorage.getItem", "Authorization")))
            NavigationManager.NavigateTo("/usercenter");
        await base.OnInitializedAsync();
    }

    private async Task OnFinish(EditContext editContext)
    {
        var authUrl = AuthUrl + $"/connect/authorize?response_type=code&client_id=Blog_Blazor&redirect_uri={SelfUrl}/login-callback&scope=Blog";
        if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
        {
            await _message.Error("用户名或密码不能为空！");
            return;
        }
        var loginResult = await LoginAsync();
        if (loginResult.Result == 1)
        {
            await JSRuntime.InvokeVoidAsync("openNew", authUrl, "_blank");
            //await HttpClient.GetAsync(authUrl);
        }
        else if(loginResult.Result == 2)
        {
            await _message.Error("用户名或密码错误！");
            return;
        }
        var token = "";
        while (string.IsNullOrEmpty(token))
        {
            token = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "Authorization");
            //token = await sessionStorage.GetItemAsync<string>("Authorization");
            Console.WriteLine(token);
            await Task.Delay(500);
        }
        NavigationManager.NavigateTo("/", true);
    }

    private void OnFinishFailed(EditContext editContext)
    {
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
    }

    public async Task<LoginResultDto> LoginAsync()
    {
        var dto = new
        {
            userNameOrEmailAddress = model.Username,
            password = model.Password,
            rememberMe = true
        };
        string url = "/api/account/login";
        StringContent content = new StringContent(JsonSerializer.Serialize(dto), Encoding.UTF8, "application/json");
        var result = await HttpClient.PostAsync(url, content);
        return await result.Content.ReadFromJsonAsync<LoginResultDto>();
    }
}
